import type { Router } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/public/user'
import await_to from 'await-to-js'
NProgress.configure({ showSpinner: false })

export type Options = {
  whiteList?: string[]
}

export const interceptors = (router: Router, options: Options) => {
  const whiteList = options.whiteList || ['/login']
  router.beforeEach(async (to, from, next) => {
    // 开启进度条
    NProgress.start()
    // 设置标题
    if (typeof to.meta.title === 'string') {
      document.title = to.meta.title || import.meta.env.VITE_SYS_NAME
    }

    const UserStore = useUserStore()
    // 确定用户是否已登录过，存在Token
    const hasToken = UserStore.token
    if (hasToken) {
      try {
        if (UserStore.userInfo?.userId) {
          next()
          return
        }
        const [err] = await await_to(UserStore.getInfo())
        if (err) {
          UserStore.logout().then(() => {
            next({ path: '/' })
          })
          return
        } else {
          next()
        }
      } catch (error) {
        window.location.href = `/login`
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        window.location.href = `/login`
      }
    }
  })

  router.afterEach(() => {
    NProgress.done()
  })
}
